<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >产品管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}产品</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        :rules="pageRules"
        ref="pageForm"
      >
        <ContainerTitle>基本信息
          <Tip
            inline
            v-if="['create', 'edit'].includes(pageAction)"
          >（已停用的平台、客户、产品名称无法选择）</Tip>
        </ContainerTitle>
        <el-form-item
          required
          label="平台名称："
        >
          <el-select
            size="small"
            class="u-w350"
            placeholder="请选择平台"
            filterable
            :disabled="['edit', 'detail'].includes(pageAction)"
            v-model="pageData.platformId"
          >
            <el-option
              v-for="item in platformOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          required
          label="客户名称："
        >
          <el-select
            class="u-w350"
            size="small"
            placeholder="请选择客户"
            filterable
            :disabled="['edit', 'detail'].includes(pageAction)"
            v-model="pageData.customerId"
            @change="fetchConnectOptions(pageData.customerId)"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          required
          label="产品名称："
        >
          <el-select
            size="small"
            class="u-w350"
            placeholder="请选择产品"
            filterable
            :disabled="pageAction === 'detail'"
            v-model="pageData.productNameId"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <ContainerTitle>其他信息</ContainerTitle>
        <el-form-item label="客户负责人：">
          <el-select
            size="small"
            class="u-w350"
            placeholder="请选择客户负责人"
            filterable
            :disabled="pageAction === 'detail'"
            v-model="pageData.principalId"
          >
            <el-option
              v-for="item in connectOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="考核要求："
        >
          <el-input
            size="small"
            class="u-w350"
            type="textarea"
            placeholder="请输入考核要求"
            :disabled="pageAction === 'detail'"
            rows="5"
            maxlength="200"
            v-model.trim="pageData.assess"
          ></el-input>
        </el-form-item>

        <template v-if="pageAction === 'detail'">
          <el-form-item label="我方运营最新返点："><span v-html="getCurrentRetabes(pageData.ourRetabes)"></span></el-form-item>
          <el-form-item label="客户运营最新返点："><span v-html="getCurrentRetabes(pageData.customerRetabes)"></span></el-form-item>
          <el-form-item label="服务费率："><span v-html="getCurrentServeRetabes(pageData.serviceRate)"></span></el-form-item>
          <el-form-item label="AE负责人："><span v-html="getCurrentAe(pageData.aePrincipal,pageData.aeDate)"></span></el-form-item>
          <el-form-item label="商务负责人："><span v-html="getCurrentAe(pageData.businessPrincipal,pageData.businessDate)"></span></el-form-item>
          <el-form-item label="产品状态：">{{mapOptionLabel(PRODUCE_STATUS_OPTION, pageData.status)}}</el-form-item>
          <el-form-item
            label="投放时间："
            v-if="pageData.status === 4"
          >{{pageData.startDate}}</el-form-item>
          <el-form-item
            label="停投时间："
            v-if="pageData.status === 5"
          >{{pageData.stopDate}}</el-form-item>
          <el-form-item
            label="停投原因"
            v-if="pageData.status === 5"
          >{{pageData.stopReason}}</el-form-item>
          <el-form-item label="关联账号：">
            <el-button
              v-if="pageData.accountCount > 0"
              type="text"
              size="small"
              @click="$router.push({
                name: 'flow-account',
                query: {
                  productId: pageData.productNameId,
                  platformId: pageData.platformId,
                  customerId: pageData.customerId
                }
              })"
            >{{pageData.accountCount}}</el-button>
            <template v-else>{{pageData.accountCount}}</template>
          </el-form-item>
          <el-form-item label="最后操作人：">{{pageData.updateBy}}</el-form-item>
          <el-form-item label="最后操作时间：">{{pageData.updateTime}}</el-form-item>
        </template>
      </el-form>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="$router.back()"
        >返回</el-button>
        <el-button
          v-if="['create', 'edit'].includes(pageAction)"
          size="small"
          type="primary"
          @click="handleEnsure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";
import Tip from "@/components/tip";

import { mapOptionLabel, getStrLen } from "@/util";
import { PRODUCE_STATUS_OPTION } from "@/assets/js/flow-option";

export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup,
    Tip
  },
  data() {
    return {
      PRODUCE_STATUS_OPTION,

      pageAction: this.$route.query.action,

      // 下拉
      platformOptions: [],
      customerOptions: [],
      productOptions: [],
      connectOptions: [],

      pageData: {
        platformId: null,
        customerId: null,
        productNameId: null,
        principalId: null,
        assess: ""
      },
      pageRules: {
        platformId: {
          required: true,
          message: "请选择平台名称",
          trigger: ["change", "blur"]
        },
        customerId: {
          required: true,
          message: "请选择客户名称",
          trigger: ["change", "blur"]
        },
        productNameId: {
          required: true,
          message: "请选择产品名称",
          trigger: ["change", "blur"]
        },
        assess: {
          validator: (rule, value, callback) => {
            if (getStrLen(value) > 200) {
              callback(new Error("考核要求最多200个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    mapOptionLabel,

    // 下拉
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status:["edit", "detail"].includes(this.pageAction) ? 0 : 2
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = res.data.data;
        }
      });
    },
    fetchProductOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product_name/get_product_name",
        params: {
          status: ["edit", "detail"].includes(this.pageAction) ? 0 : 2
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.productOptions = res.data.data;
        }
      });
    },
    fetchPlatformOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status:["edit", "detail"].includes(this.pageAction) ? 0 : 2,
          customerId: 0,
          productId: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = res.data.data;
        }
      });
    },
    fetchConnectOptions(customerId) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_principal_by_id",
        params: {
          customerId
        }
      }).then(res => {
        if (res.data.code === 0) {
          console.log(res.data.data)
          this.connectOptions = res.data.data;
        }
      });
    },

    // 确定
    handleEnsure() {
      if (this.pageAction === "edit") {
        this.updateDetail();
      } else {
        this.createDetail();
      }
    },
    // 新建
    createDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/product/add",
            data: this.pageData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("新建成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 编辑
    updateDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/product/update",
            data: this.pageData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("修改成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 详情
    getDetail() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_by_id",
        params: {
          productId: this.$route.query.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          if (this.pageAction === "edit") {
            let {
              id,
              platformId,
              customerId,
              productNameId,
              principalId,
              assess
            } = res.data.data;
            this.pageData = {
              id,
              platformId,
              customerId,
              productNameId,
              principalId,
              assess
            };
          } else {
            this.pageData = res.data.data;
          }
          this.fetchConnectOptions(this.pageData.customerId);
        }
      });
    },
    // 最新返点
    getCurrentRetabes(data = []) {
      let len = data.length;
      if (len) {
        let item = data[len - 1];
        return `${item.rebates}%（${item.startDate}）`;
      }
      return '-';
    },
    getCurrentServeRetabes(data = []) {
      let len = data.length;
      if (len) {
        let item = data[len - 1];
        return `${item.serviceRate}%（${item.startDate}）`;
      }
      return '-';
    },
    getCurrentAe(people,date){
      
      let sPeople = people== null ?'-': people
      let sDate = date==null ? '-' : date
      if(people== null&& date==null  )return '-'
      return `${sPeople}(${sDate})`
    }
  },
  created() {
    this.fetchCustomerOptions();
    this.fetchProductOptions();
    this.fetchPlatformOptions();
    if (["edit", "detail"].includes(this.pageAction)) {
      this.getDetail();
    }
  }
};
</script>